package com.example.udpLearn.udp2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 客户端发送一次数据接收一次数据，服务端接收一次数据发送一次数据：服务端
 */
public class Server {
    public static void main(String[] args) throws IOException {

        System.out.println("服务端启动...");

        DatagramSocket socket = new DatagramSocket(8888);

        /**
         * 接收客户端数据
         */
        byte[] serverReceive = new byte[1024 * 64];
        DatagramPacket packetReceive = new DatagramPacket(serverReceive, serverReceive.length);

        socket.receive(packetReceive);

        System.out.println("地址：" + packetReceive.getAddress());
        System.out.println("端口：" + packetReceive.getPort());
        System.out.println("服务端接收到数据：" + new String(serverReceive, 0, packetReceive.getLength()));


        /**
         * 服务端发送数据
         */
        byte[] serverSend = "已经接收到了数据".getBytes();
        DatagramPacket packetSend = new DatagramPacket(serverSend, serverSend.length, packetReceive.getAddress(), packetReceive.getPort());

        socket.send(packetSend);

        /**
         * 释放资源
         */
        socket.close();

    }
}
